#导入必要的库
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb

#加载数据
iris_data = pd.read_csv('iris.data')
#由于这个数据没有列名， 所以先给每个列取个名字。
iris_data.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class']
print(iris_data.head(5))

#先看数据有无缺失值，最大最小，均值等基本情况
print(iris_data.describe())

#绘制图形来观察数据的大致分布
plt.figure(figsize=(10, 10))
for column_index, column in enumerate(iris_data.columns):
    if column == 'class':
        continue
    plt.subplot(2, 2, column_index + 1)
    sb.violinplot(x='class', y=column, data=iris_data)
plt.show()

from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

all_inputs = iris_data[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']]
all_classes = iris_data['class'].values
decision_tree_classifier = DecisionTreeClassifier()

# 划分训练集与测试集
(training_inputs, testing_inputs, training_classes, testing_classes) = (
    train_test_split(all_inputs, all_classes,test_size=0.25, random_state=1))

# 在训练集上训练分类器
decision_tree_classifier.fit(training_inputs, training_classes)
# 使用分类准确性在测试集上验证分类器
accuracy = decision_tree_classifier.score(testing_inputs, testing_classes)

print(f"决策树的准确率: {accuracy:.2f}")

from sklearn.model_selection import cross_val_score
import numpy as np
cv_scores = cross_val_score(decision_tree_classifier,all_inputs,all_classes,cv=10)
#cross_val_score返回我们可以想象的分数列表
#对分类器的性能进行合理评估
print(cv_scores)
sb.histplot(cv_scores)
plt.title('Average score:{}'.format(np.mean(cv_scores)))
plt.show()


